package binarytree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/22 21:06
 * https://leetcode-cn.com/problems/merge-two-binary-trees/
 * 给你两棵二叉树： root1 和 root2 。
 *
 * 想象一下，当你将其中一棵覆盖到另一棵之上时，两棵树上的一些节点将会重叠（而另一些不会）。
 * 你需要将这两棵树合并成一棵新二叉树。合并的规则是：如果两个节点重叠，那么将这两个节点的值相加作为合并后节点的新值；
 * 否则，不为 null 的节点将直接作为新二叉树的节点。返回合并后的二叉树。
 */
public class MergeTrees {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 递归法
     * @param root1
     * @param root2
     * @return
     */
    public static TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }
        //修改root1的值
        root1.val +=root2.val;
        root1.left = mergeTrees(root1.left, root2.left);
        root1.right = mergeTrees(root1.right, root2.right);
        return root1;
    }

    /**
     * 迭代法
     * @param root1
     * @param root2
     * @return
     */
    public static TreeNode mergeTrees1(TreeNode root1, TreeNode root2) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }
        queue.offer(root1);
        queue.offer(root2);
        while (!queue.isEmpty()) {
            TreeNode node1 = queue.poll();
            TreeNode node2 = queue.poll();
            node1.val +=node2.val;
            if (node1.left != null && node2.left != null) {
                queue.offer(node1.left);
                queue.offer(node2.left);
            }
            if (node1.left == null && node2.left != null) {
                node1.left = node2.left;
            }
//            if (node1.left != null && node2.left == null) {
//             //node2结点为空，不处理
//            }
            if (node1.right != null && node2.right != null) {
                queue.offer(node1.right);
                queue.offer(node2.right);
            }
            if (node1.right == null && node2.right != null) {
                node1.right = node2.right;
            }
        }
        return root1;
    }

    public static void main(String[] args) {
        TreeNode root1 = new TreeNode(1);
        root1.left = new TreeNode(3);
        TreeNode root2 = new TreeNode(2);
        TreeNode treeNode = mergeTrees(root1, root2);
        System.out.println();
    }
}
